package com.wjl.shop.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 导出表格
 * @author YangGuo
 * @version 1.0
 * @date 2021/10/12 15:15
 */
public class ExportExcel {
    public static final int INIT_COUNT=0;
    public static final String SKP="serialVersionUID";
    public static HSSFWorkbook export(List<?> objectLists) throws IllegalAccessException {
        int rows=INIT_COUNT;
        final HSSFWorkbook body = new HSSFWorkbook();
        final HSSFSheet sheet = body.createSheet("exportData");
        Field[] fields=null;
        //设置表头
        if(objectLists.size()>0){
            Object o = objectLists.get(0);
            fields = o.getClass().getDeclaredFields();
            HSSFRow row = sheet.createRow(rows++);
            int clo=INIT_COUNT;
            for(Field field:fields){
                if(field.getName().equals(SKP)) {continue;}
                HSSFCell cell = row.createCell(clo++);
                cell.setCellValue(field.getName());
            }
        }else {return body;}
        //填表
        while(objectLists.size()>0){
            Object o = objectLists.get(0);
            HSSFRow newRow = sheet.createRow(rows++);
            int clo=INIT_COUNT;
            for(Field field:fields){
                if(field.getName().equals(SKP)) {continue;}
                field.setAccessible(true);
                Object o1 = field.get(o);
                HSSFCell cell = newRow.createCell(clo++);
                cell.setCellValue(o1+"");
            }
            objectLists.remove(0);
        }
        return body;
    }
}
